package per.ethan.javase.thread;

import java.util.Random;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Ethan
 * @date 2020/04/27 14:30
 */
public class LockDemo {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        for (int i = 0; i < 3; i++) {
            new Thread(ticket, "售票窗口" + i).start();
        }
    }

}

class Ticket implements Runnable {

    private int ticketNum = 1000;

    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();

                if (ticketNum > 0) {
                    Thread.sleep(new Random().nextInt(10));
                    System.out.println(Thread.currentThread().getName() + "-> 余票：" + --ticketNum);
                } else {
                    break;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

}
